<template>
	<div class="back-to-dom">
		<slot>
			<el-button :loading="loading" type="warning" size="medium" @click="toOpenDomList">回到指定节点</el-button>
		</slot>

		<el-dialog :visible.sync="visible" title="退回结果">
			<el-table :data="domList" border>
				<el-table-column width="50">
					<template #default="{row: {nodeId}}">
						<el-radio v-model="checkNode" :label="nodeId">{{ "" }}</el-radio>
					</template>
				</el-table-column>
				<el-table-column label="节点名" prop="nodeName"></el-table-column>
			</el-table>

			<template #footer>
				<el-button @click="onCancel" size="medium" type="danger">取 消</el-button>
				<el-button :loading="submitLoading" type="primary" size="medium" @click="onSubmit">确 定</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script>
import request from "@/common/request"

export default {
	data() {
		return {
			domList: [],
			loading: false,
			visible: false,

			checkNode: "",
			submitLoading: false,
		}
	},
	computed: {},
	created() {},
	methods: {
		async toOpenDomList() {
			try {
				await this.getList()
				this.visible = !!this.domList.length
			} catch (error) {
				return
			}
		},
		onCancel() {
			this.visible = false
			this.checkNode = ""
		},
		async onSubmit() {
			if (!this.checkNode) {
				this.$message.error("请选择回退节点")
				return
			}
			if (this.submitLoading) return
			this.submitLoading = true
			try {
				await this.backToNode()
				this.$message.success("回退成功")
				this.onCancel()
				this.$router.go(-1)
			} catch (error) {
				this.$message.error("回退失败")
			} finally {
				this.submitLoading = false
			}
		},

		async autoSubmitLast() {
			try {
				await this.getList()

				if (this.domList.length) {
					const lastNode = this.domList.at(-1)

					this.checkNode = lastNode.nodeId

					await this.backToNode()
				}
			} catch (error) {
				// todo
			}
		},

		async getList() {
			this.loading = true
			try {
				const { data } = await request("post", "/flowable/approves/getAllBackNodes", {
					...this.$route.query,
				})

				this.domList = data || []

				if (!this.domList.length) {
					throw new Error("没有可回退的节点")
				}
			} catch (error) {
				this.$message.error((error && error.message) || "获取回退节点失败")
			} finally {
				this.loading = false
			}
		},
		async backToNode() {
			await request("post", "/flowable/approves/backToNode", {
				...this.$route.query,
				nodeId: this.checkNode,
			})
		},
	},
	components: {},
}
</script>

<style lang="scss" scoped>
.expand {
	padding-inline: 30px;
}
.member-status {
	display: inline-block;
	padding: 0 5px;
	border-radius: 2px;
	font-size: 12px;
	line-height: 20px;
	text-align: center;
	color: #fff;
	&.success {
		background-color: #67c23a;
	}
	&.error {
		background-color: #f56c6c;
	}
}
</style>
